package crypto

import (
	"io/ioutil"

	"hundsun.com/hsl/hschain/common/config"
)

var caCert []byte
var localCert []byte

const (
	//ConfigKeyCaCertPath ca cert path
	ConfigKeyCaCertPath = "chain.caCertPath"
	//ConfigKeyLocalCertPath local cert path
	ConfigKeyLocalCertPath = "chain.localCertPath"
	//ConfigKeyEnablePrivateCa if enable private ca
	ConfigKeyEnablePrivateCa = "chain.enablePrivateCa"
)

//EnableAuthVerify 是否启用证书校验
func EnableAuthVerify() bool {
	return config.GetStringConfigValue(ConfigKeyCaCertPath, "") != ""
}

//GetCaCertFile get ca cert file
func GetCaCertFile() ([]byte, error) {
	if !EnableAuthVerify() {
		return nil, nil
	}
	if caCert == nil {
		caCertFile, err := ioutil.ReadFile(config.GetStringConfigValue(ConfigKeyCaCertPath, ""))
		if err != nil {
			return nil, err
		}
		caCert = caCertFile
		return caCertFile, nil
	}
	return caCert, nil
}

//GetLocalCertFile get local server cert file
func GetLocalCertFile() ([]byte, error) {
	if !EnableAuthVerify() {
		return nil, nil
	}
	if localCert == nil {
		serverCertFile, err := ioutil.ReadFile(config.GetStringConfigValue(ConfigKeyLocalCertPath, ""))
		if err != nil {
			return nil, err
		}
		localCert = serverCertFile
		return serverCertFile, nil
	}
	return localCert, nil
}

//EnablePrivateCa whether enable private ca
func EnablePrivateCa() bool {
	return config.GetBoolConfigValue(ConfigKeyEnablePrivateCa, false)
}
